package com.rzico.sbl.ui.statistic

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityUnionOrderBinding
import com.rzico.sbl.model.*
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.order.DeliverDetailActivity
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.StatisticUnionViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class UnionOrderActivity : BaseActivity(R.layout.activity_union_order) {

    private val mBinding by lazy { ActivityUnionOrderBinding.bind(getRootView()) }

    private lateinit var mDateMode: String
    private var mEnterpriseId = ""
    private var mEnterpriseName = ""
    private var mOrderType = ""
    private var mBeginDate = ""
    private var mEndDate = ""

    private val mStationList = ArrayList<UnionFilter>()
    private val mFilterList = ArrayList<FilterData>()

    override fun getViewModel() = get<StatisticUnionViewModel>()

    override fun initData() {
        initTitle(title = "订单统计")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
        getStationList()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关订单信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                mAdapter = SlimAdapter.creator()
                    .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_time, bean.hint + bean.time)
                            text(R.id.item_order_status, bean.status_hint)

                            clicked {
                                when (mOrderType) {
                                    "out" ->
                                        startActivityEx<OrderDetailActivity>(
                                            "orderSn" to bean.orderSN,
                                            "shippingSn" to bean.shippingSn,
                                        )

                                    "in" ->
                                        startActivityEx<DeliverDetailActivity>(
                                            "orderSn" to bean.orderSN,
                                            "shippingSn" to bean.shippingSn
                                        )
                                }
                            }
                        }
                    }
                    .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                            text(R.id.item_order_price, "单价：${bean.price.formatDecimal()}元")
                            text(R.id.item_order_num, "x${bean.quantity}")

                            visibility(
                                R.id.item_order_img_label,
                                visibleValue { bean.first }
                            )

                            with<ImageView>(R.id.item_order_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<ImageView>(R.id.item_order_img_type) {
                                when (bean.methodDescr) {
                                    "offline" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order03)
                                    }

                                    "eleme", "elemengc" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order04)
                                    }

                                    "meituan" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order05)
                                    }

                                    "nongfu" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order06)
                                    }

                                    "jd" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order10)
                                    }

                                    "taobao" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order11)
                                    }

                                    "pinduoduo" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order12)
                                    }

                                    "dummy" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order22)
                                    }

                                    "ali" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order26)
                                    }

                                    else -> it.gone()
                                }
                            }

                            with<ImageView>(R.id.item_order_img_status) {
                                when {
                                    bean.hopeDate.isNotEmpty() && !bean.fast -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order02)
                                    }

                                    bean.hopeDate.isNotEmpty() && bean.fast -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order07)
                                    }

                                    else -> it.gone()
                                }
                            }

                            clicked {
                                when (mOrderType) {
                                    "out" ->
                                        startActivityEx<OrderDetailActivity>(
                                            "orderSn" to bean.orderSN,
                                            "shippingSn" to bean.shippingSn,
                                        )

                                    "in" ->
                                        startActivityEx<DeliverDetailActivity>(
                                            "orderSn" to bean.orderSN,
                                            "shippingSn" to bean.shippingSn
                                        )
                                }
                            }
                        }
                    }
                    .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                        jector.apply {
                            visible(R.id.item_order_settle_ll)
                            text(R.id.item_order_count, bean.total_num)
                            text(R.id.item_order_total, bean.amount.formatDecimal())
                            text(R.id.item_order_total_hint, bean.amountHint)
                            text(R.id.item_order_settle, bean.settlementPrice)
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_phone, bean.phone)
                            text(R.id.item_order_addr, bean.address)
                            text(R.id.item_order_yu, bean.estimateDate)
                            text(R.id.item_order_cmemo, bean.cardMemo)
                            text(R.id.item_order_bmemo, bean.memo)
                            text(R.id.item_order_smemo, bean.shipMemo)

                            getView<View>(R.id.item_order_settle_ll)
                                .isVisible = mOrderType == "out"
                            getView<View>(R.id.item_order_yu_ll)
                                .isGone = bean.estimateDate.isEmpty()
                            getView<View>(R.id.item_order_cmemo_ll)
                                .isGone = bean.cardMemo.isEmpty()
                            getView<View>(R.id.item_order_bmemo_ll)
                                .isGone = bean.memo.isEmpty()
                            getView<View>(R.id.item_order_smemo_ll)
                                .isVisible = bean.shipMemo.isNotEmpty()

                            with<TextView>(R.id.item_order_pei) { tv ->
                                when (mOrderType) {
                                    "out" -> {
                                        tv.text = "配送站点：${bean.enterpriseName}"
                                        tv.isGone = bean.enterpriseName.isEmpty()
                                    }

                                    "in" -> {
                                        tv.text =
                                            "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                        tv.isGone = bean.adminName.isEmpty()
                                    }
                                }
                            }

                            clicked {
                                when (mOrderType) {
                                    "out" ->
                                        startActivityEx<OrderDetailActivity>(
                                            "orderSn" to bean.orderSN,
                                            "shippingSn" to bean.shippingSn,
                                        )

                                    "in" ->
                                        startActivityEx<DeliverDetailActivity>(
                                            "orderSn" to bean.orderSN,
                                            "shippingSn" to bean.shippingSn
                                        )
                                }
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    override fun initListener() {
        mOrderType = intent.getExtra("type")
        mEnterpriseId = intent.getExtra("enterpriseId")
        mEnterpriseName = intent.getExtra("enterpriseName")
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        mBinding.apply {
            when (mOrderType) {
                "in" -> {
                    orderType.text = "接收订单"
                    getViewModel().mTypeList[1].isChecked = true
                }

                else -> {
                    mOrderType = "out"
                    orderType.text = "转出订单"
                    getViewModel().mTypeList[0].isChecked = true
                }
            }

            mEnterpriseId.notEmpty {
                orderZhan.text = mEnterpriseName
                orderZhan.setTextColor(getColorEx(R.color.colorAccent))
                orderZhanArrow.setImageResource(R.mipmap.icon_member02)
            }

            // 今日、昨日、近7天、本月、上月、本年、自定义
            when (mDateMode) {
                "1" -> {
                    orderTime.text = "今日"
                    getViewModel().mFilterTime[0].isChecked = true
                }

                "2" -> {
                    orderTime.text = "昨日"
                    getViewModel().mFilterTime[1].isChecked = true
                }

                "3" -> {
                    orderTime.text = "近7天"
                    getViewModel().mFilterTime[2].isChecked = true
                }

                "5" -> {
                    orderTime.text = "上月"
                    getViewModel().mFilterTime[4].isChecked = true
                }

                "6" -> {
                    orderTime.text = "本年"
                    getViewModel().mFilterTime[5].isChecked = true
                }

                "7" -> {
                    orderTime.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mFilterTime[6].isChecked = true
                }

                else -> {
                    mBeginDate = getFirstDate()
                    mEndDate = getEndDate()

                    orderTime.text = "本月"
                    getViewModel().mFilterTime[3].isChecked = true
                }
            }

            orderTypeLl
                .oneClick {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            orderTop,
                            getViewModel().mTypeList,
                            orderType,
                            orderTypeArrow
                        ) {
                            orderType.setTextColor(getColorEx(R.color.colorAccent))
                            orderTypeArrow.setImageResource(R.mipmap.icon_member02)

                            mOrderType = it.id

                            // 清除配送站点
                            mEnterpriseId = ""
                            mEnterpriseName = ""
                            orderZhan.text = "选择站点"
                            orderZhan.setTextColor(getColorEx(R.color.black))
                            orderZhanArrow.setImageResource(R.mipmap.icon_member01)
                            getStationList()

                            updateList()
                        }
                }

            orderZhanLl
                .oneClick {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            orderTop,
                            mFilterList,
                            orderZhan,
                            orderZhanArrow
                        ) {
                            if (it.id.isEmpty()) {
                                orderZhan.setTextColor(getColorEx(R.color.black))
                                orderZhanArrow.setImageResource(R.mipmap.icon_member01)
                            } else {
                                orderZhan.setTextColor(getColorEx(R.color.colorAccent))
                                orderZhanArrow.setImageResource(R.mipmap.icon_member02)
                            }

                            mEnterpriseId = it.id
                            mEnterpriseName = it.name
                            updateList()
                        }
                }

            orderTimeLl
                .oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            orderTime,
                            orderTimeArrow,
                            orderTop,
                            getViewModel().mFilterTime
                        ) { bean ->

                            (bean.id != "7")
                                .condition {
                                    getViewModel()
                                        .mFilterTime
                                        .last()
                                        .name = "自定义时间"
                                }

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    getStationList()
                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    getStationList()
                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getBeforeDate(6)
                                    mEndDate = getTodayDate()

                                    getStationList()
                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    getStationList()
                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    getStationList()
                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    getStationList()
                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mFilterTime
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mFilterTime
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            orderTime.text = bean.name

                                            getStationList()
                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
        }
    }

    /**
     * 水站列表
     */
    private fun getStationList() {
        getViewModel()
            .stationList(
                type = mOrderType,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mStationList.clear()
                    mStationList.addItems(list)

                    mFilterList.apply {
                        clear()

                        add(
                            FilterData(
                                "全部",
                                "",
                                "选择站点",
                                mEnterpriseId.isEmpty()
                            )
                        )

                        mStationList
                            .mapTo(this) {
                                FilterData(
                                    it.name.orEmpty(),
                                    it.enterpriseId,
                                    it.name.orEmpty()
                                )
                            }

                        mEnterpriseId
                            .notEmpty {
                                this@apply
                                    .firstOrNull { it.id == this }
                                    ?.let {
                                        it.name = mEnterpriseName
                                        it.hint = mEnterpriseName
                                        it.isChecked = true
                                    }
                                    ?: kotlin.run {
                                        add(
                                            FilterData(
                                                mEnterpriseName,
                                                this,
                                                mEnterpriseName,
                                                true
                                            )
                                        )
                                    }
                            }
                    }
                }
            )
    }

    /**
     * 消费记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderList(
                page = index,
                type = mOrderType,
                enterpriseId = mEnterpriseId,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { total, data ->
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(data)
                        data.notEmpty { pageNum++ }
                    }

                    mBinding.apply {
                        orderCount.text = total.toString()

                        mEnterpriseId
                            .isEmpty()
                            .conditionElse(
                                actionTrue = {
                                    orderNum.text =
                                        mStationList
                                            .sumOf { it.subQuantity.intValue }
                                            .toString()
                                    orderPrice.text =
                                        mStationList
                                            .sumOf { it.subPrice.doubleValue }
                                            .formatDecimal()
                                },
                                actionFalse = {
                                    mStationList
                                        .firstOrNull { it.enterpriseId == mEnterpriseId }
                                        ?.let {
                                            orderNum.text = it.subQuantity
                                            orderPrice.text = it.subPrice.formatDecimal()
                                        }
                                        ?: kotlin.run {
                                            orderNum.text = "0"
                                            orderPrice.text = "0.00"
                                        }
                                }
                            )
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}